package com.imooc.jdbc.hrapp.command;

import com.imooc.jdbc.common.DbUtils;

import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;

public class InsertCommand implements Command{


    @Override
    public void execute() {
        Scanner in = new Scanner(System.in);

        System.out.println("请输入员工部门：");
        String depName = in.next();

        System.out.println("请输入员工姓名：");
        String empName = in.next();

        System.out.println("请输入员工薪资：");
        float salary = in.nextFloat();

        System.out.println("请输入员工入职日期：");
        String strHireDate = in.next();

        Connection conn = null;
        PreparedStatement preStmt = null;

        //String转到java.sql.Date分两步

        // 1.String转为java.util.Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        java.util.Date udHireDate = null;

        try {
            udHireDate = sdf.parse(strHireDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 2. java.util.Date转为java.sql.Date
        long time = udHireDate.getTime(); //Returns the number of milliseconds since January 1, 1970

        java.sql.Date sdHireDate = new java.sql.Date(time);

        int cnt = 0;
        try {
            conn = DbUtils.getConnection();
            String insertSql = "INSERT INTO employee (dep_name,emp_name,salary, hire_date) VALUES (?,?,?,?)";
            preStmt = conn.prepareStatement(insertSql);

            preStmt.setString(1, depName);
            preStmt.setString(2, empName);
            preStmt.setFloat(3,salary);
            preStmt.setDate(4, sdHireDate);

            cnt = preStmt.executeUpdate();

            System.out.println("cnt:" + cnt);
            System.out.println("员工入职手续已办理");

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeConnection(null, preStmt, conn);
        }



//        if(res > 1){
//
//        }

    }
}
